<?php
namespace app\lib\exception;
use think\Exception;
use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;
use \app\lib\exception\BaseException as BaseException;

class ExceptionHandler extends Handle
{
    /**
     * @var string
     */
    private $code;
    /**
     * @var string
     */
    private $msg;
    /**
     * @var string
     */
    private $errorCode;

    public function render($request, Throwable $e): Response
    {
//        // 参数验证错误
//        if ($e instanceof ValidateException) {
//            return json($e->getError(), 422);
//        }
//
//        // 请求异常
//        if ($e instanceof HttpException && $request->isAjax()) {
//            return response($e->getMessage(), $e->getStatusCode());
//        }
//
//        // 其他错误交给系统处理
//        return parent::render($request, $e); // TODO: Change the autogenerated stub
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
            $this->recordErrorLog($e);
//            return json($e->getError(), 422);
        }else{
            if(env('APP_DEBUG'))
            {
                return parent::render($request, $e);
            }else{
                $this->code = 500;
                $this->msg = '内部错误';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }
        }
        $result = [
            'msg'=>$this->msg,
            'error_code'=>$this->errorCode,
            'request_url'=>$request->url()
        ];
        return json($result,$this->code);
    }
    private function recordErrorLog(Exception $e)
    {
//        Log::init([
//            'type'=>'File',
//            'path'=>LOG_PATH,
//            'level'=>['error']
//        ]);
        Log::record($e->getMessage(),'error');
    }
}